<template>
  <div id="app" class="login login-main">
    <!--      <img src="../assets/back.jpg">-->

    <div class="login-frame" v-if="IsLogin">
      <el-row type="flex" justify="center">
        <!-- justify 对齐方式 -->
        <el-col :span="6">
          <el-card shadow="always">

            <div class="block" v-for="fit in fits" :key="fit">
              <el-avatar :size="80" :src="circleUrl" :fit="fit"></el-avatar>
            </div>
            <!--              <span class="iconfont icon-xiazai" style="width: 200px;height: 205px"></span>-->
            <!--          <h1 style="text-align: center;">欢迎登陆</h1>-->
            <el-divider></el-divider>
            <!-- form表单 -->
            <el-form :model="nameValidateForm" ref="nameValidateForm" label-width="100px" class="demo-ruleForm"
                     @keyup.enter.native="submitForm('nameValidateForm')">
              <!-- 用户名 -->

              <el-form-item
                prop="name"
                :rules="[
                      { required: true, message: '用户名不能为空'},
                      ]"
              >
                <el-input placeholder="请输入用户名" type="text" clearable v-model="nameValidateForm.name" autocomplete="off"
                          prefix-icon="el-icon-user"></el-input>
              </el-form-item>

              <!-- 密码 -->
              <el-form-item
                prop="password"
                :rules="[
                      { required: true, message: '密码不能为空'},
                      ]"
              >
                <el-input placeholder="请输入密码" clearable v-model="nameValidateForm.password" show-password
                          prefix-icon="el-icon-lock"></el-input>
              </el-form-item>
              <el-checkbox class="remember-me" v-model="checked" @change="isCheckBoxed">记住密码</el-checkbox>
              <el-link type="primary" :underline="false" class="forget-password" style="width: 100px">忘记密码？</el-link>
              <!-- 按钮 -->
              <!--                    <el-button type="success" plain>成功按钮</el-button>-->
              <el-button type="success" @click="submitForm('nameValidateForm')" class="login-now">立即登录</el-button>
              <el-button @click="resetForm('nameValidateForm')" class="reset">重置</el-button>
              <el-form-item id="register-box">
                <label class="register">没有账号？
                  <el-link type="primary" @click="OpenRegister" class="register-link" :underline="false">去注册
                  </el-link>
                </label>
              </el-form-item>

            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!--注册-->
    <div class="Register-frame" v-else>
      <!--    需加这个，append-to-body不然弹窗会变暗-->
      <el-dialog title="注册账号" :visible.sync="OpenRegisterFrame" class="registerFrame" append-to-body
                 @close="IsLogin=true">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
          <el-form-item label="密码" :label-width="formLabelWidth" prop="newPwd" required>
            <el-input placeholder="请输入密码" clearable v-model="ruleForm.newPwd" type="password" show-password
                      prefix-icon="el-icon-lock" autocomplete="off" class="register-input"></el-input>
          </el-form-item>
          <el-form-item label="确认" :label-width="formLabelWidth" prop="confirmPwd" required>
            <el-input placeholder="再次确认密码" clearable v-model="ruleForm.confirmPwd" show-password
                      prefix-icon="el-icon-lock" type="password" autocomplete="off" class="register-input"></el-input>
          </el-form-item>
          <el-form-item label="昵称" :label-width="formLabelWidth" prop="Nack" required>
            <el-input placeholder="请输入昵称" clearable v-model="ruleForm.Nack" prefix-icon="el-icon-s-custom"
                      autocomplete="off" type="text" class="register-input"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" :label-width="formLabelWidth" prop="Email" required>
            <el-input placeholder="请输入邮箱" clearable v-model="ruleForm.Email" prefix-icon="el-icon-message"
                      autocomplete="off" type="email" class="register-input"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="OpenRegisterFrame = false" class="cancel-btn">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')" class="ok-btn">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
/*
引入加解密文件
 */
export default {
  data() {
    // 校验
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.confirmPwd !== '') {
          this.$refs.ruleForm.validateField('confirmPwd')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.newPwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // ^[\u4e00-\u9fa5]{2,8}$
    var valNickName = (rule, value, callback) => {
      const NameReg = /^[\u4e00-\u9fa5]{2,8}$/
      if (!value) {
        return callback(new Error('昵称不能为空'))
      }
      setTimeout(() => {
        if (NameReg.test(value)) {
          callback()
        } else {
          callback(new Error('昵称格式为 2-8个中文字符'))
        }
      }, 100)
    }
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }
    return {
      checked: false,
      fits: ['fill'],
      circleUrl: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
      ruleForm: {
        newPwd: '',
        confirmPwd: '',
        Nack: '',
        Email: ''
      },
      rules: {
        newPwd: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'},
          {validator: validatePass, trigger: 'blur'}
        ],
        confirmPwd: [
          {required: true, message: '请确认密码', trigger: 'blur'},
          {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'},
          {validator: validatePass2, trigger: 'blur', required: true}
        ],
        Nack: [
          {required: true, message: '请输入昵称', trigger: 'blur'},
          {validator: valNickName, trigger: 'blur'}
        ],
        Email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ]
      },
      nameValidateForm:
        {
          name: '',
          password: ''
        },
      IsLogin: true,//是否展示登录界面
      OpenRegisterFrame: false,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formLabelWidth: '60px',
      center: true
    }
  },
  methods: {
    //记住密码
    isCheckBoxed(event) {
      this.checked = event;

    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
          if (valid) {
            if (formName === 'ruleForm') {
              let data = this.$SM4EnCrypto(JSON.stringify(this.ruleForm))
              // 向后台请求注册信息
              this.$post('register', {msg: data}).then((resp) => {
                if (resp.status === 200) {
                  if (resp.data.flag === 0) {
                    // 注册成功，返回消息及账号
                    this.RegisterSuccess(resp.data.msg, resp.data.account)
                  }
                  // 注册失败
                  else {
                    this.RegisterFail(resp.data.msg)
                  }
                }
                // 网络错误导致失败
                else {
                  this.RegisterFail(resp.data.msg)
                }
              })
                .catch((err) => {
                  this.RegisterFail('哎呀，出错啦！')
                })
              // alert("注册成功！")
            } else if (formName === 'nameValidateForm') {
              /*
            检验成功，首先都数据进行加密
            向服务器发送请求
             */
              let data = this.$SM4EnCrypto(JSON.stringify(this.nameValidateForm)) // 需要对json转字符串处理
              //testMsg需要与服务器对应
              this.$get('/login', {login: data})
                .then((response) => {
                  if (response.status === 200) {
                    //0登录成功，1登录失败
                    if (response.data.status === 200) {
                      let user = {
                        name: response.data.result.name,
                        org_id: response.data.result.org_id,
                        user_id: response.data.result.user_id,
                      }
                      /*
                     1. 登录成功，将菜单更新通过mutations中的UpdateMenus方法至state中的menus
                     2. 将用户信息更新通过mutations中的UpdateUser方法至state中的user
                       */
                      this.$store.commit('BaseStore/UpdateMenus', response.data.result.menu)
                      this.$store.commit('BaseStore/UpdateUser', user)
                      sessionStorage.setItem('token', response.data.token)
                      //登录成功显示
                      this.LoginSuccess(response.data.msg)
                    } else {
                      this.LoginFail(response.data.msg)
                    }
                  }
                })
                .catch((error) => {
                  this.LoginFail('哎呀，出错啦！')
                })
            }
          } else {
            return false
          }
        }
      )
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 注册
    RegisterSuccess(msg, account) { // 注册成功
      // 注册成功后，先把注册页面关闭后一秒再显示
      setTimeout(() => {
        this.$alert('请记住您的账号：' + account, '注册成功', {
          confirmButtonText: '确定',
          callback: action => {
            this.IsLogin = true //开启登录
            this.OpenRegisterFrame = false//关闭注册
            this.$message({
              type: 'success',
              message: msg,
            })
          }
        })
      }, 500)
    },
    RegisterFail(msg) { // 注册失败
      this.$message({
        showClose: true,
        message: msg,
        type: 'error'
      })
    },
    // 登录
    LoginSuccess(msg) { // 登录成功
      layer.msg(msg, {
        icon: 1,
        time: 1000
      })
      // this.$message({
      //   showClose: true,
      //   message: msg,
      //   type: 'success',
      //   duration: 1000 // 显示1s
      // })
      setTimeout(() => {
        // this.$router.push('index')
        this.$router.push('index')
        // 登录成功，保存该用户的token
        // 页面跳转刷新，防止停留在缓存中
        //   setTimeout(()=>{
        //登录后刷新页面，加载菜单
        //     window.location.reload();
        //   },2000)
      }, 1000)
       window.sessionStorage.setItem('rememberIsChecked', JSON.stringify({rememberChecked: this.checked}))
      if (this.checked) { //记住密码保存
        window.sessionStorage.setItem('rememberUserLogin', JSON.stringify(this.nameValidateForm))
      }
    },
    LoginFail(msg) { // 登录失败
      this.$message({
        showClose: true,
        message: msg,
        type: 'error'
      })
    },
    OpenRegister() {
      this.IsLogin = false;
      setTimeout(() => {
        this.OpenRegisterFrame = true;
      }, 500)
    },
    handleClose(done) {//不注册，点击上方X，执行函数
      this.$confirm('是否放弃注册？')
        .then(() => {
          this.IsLogin = true;
        })
        .catch(_ => {
        });

    }
  },
  created() {
    let isCheckState = window.sessionStorage.getItem('rememberIsChecked')
    isCheckState = JSON.parse(isCheckState);
    this.checked = isCheckState
    if (isCheckState) {
      let isCheckInfo = window.sessionStorage.getItem('rememberUserLogin')
      if (isCheckInfo) {
        isCheckInfo = JSON.parse(isCheckInfo)
        this.nameValidateForm.name = isCheckInfo.name;
        this.nameValidateForm.password = isCheckInfo.password;
      }
    }

  }

}
</script>

<style>
.el-radio-group {
  display: flex;
  /* 边缘 */
  justify-content: center;
}

.el-row--flex {
  display: -webkit-box;
  display: -ms-flexbox;
  /*margin-top: 100px;*/
}

.el-card {
  border-radius: 30px;
  width: 380px;
  margin-top: 48%;
  /*margin-left: 50%;*/
  /* box-shadow: 0 2px 12px 0 rgb(243, 102, 102); */
  /* box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04); */
}

.grid-content {
  /* background: rgb(14, 214, 131); */
  border-radius: 4px;
  min-height: 50px;
}

/*.el-row {*/
/*  margin-bottom: 20px;*/
/*}*/
.el-input {
  margin-left: -50px;
  width: 280px;
}

.el-form-item {
  width: 300px;
}

</style>
<style>
.remember-me, .forget-password {
  text-align: center;
}

.forget-password, .remember-me {
  width: 50%;
  height: 100%;
  margin: 0 0 20px 20px;
}

.remember-me {
  margin-left: -10px;
}

.forget-password {
  margin-top: 20px;
}

.login-now {
  width: 100px;
  margin: 0 60px 0 -60px;
}

.login-now:hover {
  font-size: 16px;
}

.reset {
  margin: 0 -80px 0 0;
}

/*注册*/
#register-box {
  margin-top: 20px;
  margin-left: 20px;
  margin-bottom: -10px;
}

.register {
  width: 100px;
  margin: 100px -130px 200px 0;
}

.register-link:hover {
  font-size: 18px;
}

/*注册页面*/
.registerFrame {
  width: 50%;
  margin-left: 25%;
}

.el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}

.register-input {
  margin-left: 10px;
}

.cancel-btn {
  margin-left: -100px;
}
</style>
<style>
/* 背景图片*/
.login-main {
  background: url(../../assets/img/back2.jpg);
  width: 100%;
  height: 100%;
  position: fixed;
  margin-top: -65px; /*上边距*/
  margin-left: -10px; /*左边距*/
  background-size: 100% 100%;
}

#app {
  margin-top: 0;
}

/*body {*/
/*  height: 723px;*/
/*  background-size: 100% 100%;*/
/*  !*background-repeat: no-repeat;*!*/
/*  background-image: url(../assets/back2.jpg);*/
/*  !*图片不随滚动条滚动*!*/
/*  background-attachment: fixed;*/
/*}*/
</style>
